﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CounterServerModel;
using System.Data;
using CounterServerModel.Authentication;

namespace SmartCounters
{
	public partial class AccountsManagement : System.Web.UI.Page
	{

		DataTable accountsTable;


		protected void Page_Load(object sender, EventArgs e)
		{
			((MainTemplate)Master).m_PagePermissionFilter = MainTemplate.k_AdminPageFilter;
		}

		protected void Page_Prerender(object sender, EventArgs e)
		{
			InformationReader infoProvider = new InformationReader();
			accountsTable = new InformationReader().GetAccountsDataTable(((MainTemplate)Master).AuthenticatedLoggedInUserCredentials);
			BindGrid();
		}

		protected void EditCommand(object sender, DataGridCommandEventArgs e)
		{
			int AccountID;
			int.TryParse(e.Item.Cells[2].Text, out AccountID);

			AccountInfo AccountToEdit = new InformationReader().GetAccountInformation(((MainTemplate)Master).AuthenticatedLoggedInUserCredentials, AccountID);

			Session[AccountDetails.k_AccountSessionKey] = AccountToEdit;

			if (!Page.ClientScript.IsStartupScriptRegistered("openForm"))
			{
				ScriptManager.RegisterStartupScript(
					AccountsManagementUpdatePanel,
					AccountsManagementUpdatePanel.GetType(),
					"openForm",
					"openUserDetailsForm();",
					true);
			}
		}

		protected void ItemCommand(object sender, DataGridCommandEventArgs e)
		{
			switch (e.CommandName)
			{
				case "DeleteCommand":
					DeleteItem(e);
				break;

				default:
					// Do nothing.
				break;
			}

		}

		private void DeleteItem(DataGridCommandEventArgs e)
		{
			String accountID = e.Item.Cells[2].Text;
			AccountInfo accountToUpdate = new AccountInfo(int.Parse(accountID));

			InformationUpdater updateProvider = new InformationUpdater();
			updateProvider.DeleteAccount(((MainTemplate)Master).AuthenticatedLoggedInUserCredentials, accountToUpdate);
		}

		private void BindGrid()
		{
			AccountsGrid.DataSource = accountsTable;
			AccountsGrid.DataBind();
		}
	}
}